package com.tanhua.admin.listeners;

import com.tanhua.autoconfig.template.AliyunGreenTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class AuditListener {

    @Autowired
    private AliyunGreenTemplate template;

    @DubboReference
    private MovementApi movementApi;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            name = "tanhua.audit.queue",
                            durable = "true"
                    ),
                    exchange = @Exchange(
                            name = "tanhua.audit.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key="audit.movement"
            )
    )
    public void audit(String movementId) {
        //1、根据动态id查询动态详情
        try {
            Movement movement = movementApi.findById(movementId);
            if(movement != null && movement.getState() == 0) {
                //2、调用工具类，审核动态的文本内容和图片内容
                Map<String, String> textScan = template.greenTextScan(movement.getTextContent());
                Map<String,String> imageScan = template.imageScan(movement.getMedias());
                if(textScan != null && imageScan != null) {
                    String textSuggestion = textScan.get("suggestion"); //文本的审核结果
                    String imageSuggestion = imageScan.get("suggestion"); //图片的审核结果
                    int state = 0;
                    if ("block".equals(textSuggestion) || "block".equals(textSuggestion)){
                        state = 2;
                    }else if("pass".equals(textSuggestion) && "pass".equals(textSuggestion)) {
                        state = 1;
                    }
                    //3、更新动态
                    if(state != 0) {
                        movementApi.updateState(movementId,state);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
